﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using XMK.Tadong.DataSearch.Biz;
using XMK.Utils;
using XMK.Tadong.Model;
using XMK.Tadong.Biz;
using System.Data;
using System.Configuration;
using System.Web.SessionState;
namespace XMK.Tadong.Web.Handlers
{
    /// <summary>
    /// SearchAutoComplete 的摘要说明
    /// </summary>
    public class SearchAutoComplete : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            string resultJson = "{\"success\":true}";
            string op = context.Request.Params.Get("optype");
            switch (op)
            {
                case "add":
                    if (!AddKeyword(context)) resultJson = "{\"success\":false}";
                    break;
                case "query":
                default:
                    resultJson = QueryKeyword(context);
                    break;
            }
            
            context.Response.ContentType = "text/json";
            context.Response.Write(resultJson);
            context.Response.End();
        }

        public string QueryKeyword(HttpContext context)
        {
            List<KeyValuePair<string, string>> paramsList = new List<KeyValuePair<string, string>>();
            paramsList.Add(new KeyValuePair<string, string>("keyw", context.Request.Params.Get("keyw_startsWith")));
            paramsList.Add(new KeyValuePair<string, string>("pagesize", "10"));
            string keyw = paramsList.ToArray().FirstOrDefault(p => p.Key.ToLower().Equals("keyw")).Value;
            string lastW = keyw.Substring(keyw.Length - 1);
            if (lastW!= " ")
            { //如果关键词中最后一个字符没有空格，查询高频词
                return QueryGKeyword(paramsList.ToArray());
            }
            else if (lastW == " ")
            {//如果关键词中最后一个字符有空格，查询扩展词

                return QueryEKeyword(keyw);
            }
            SearchKeywordBiz keywBiz = new SearchKeywordBiz();
            var keywordList = keywBiz.QueryKeyword(paramsList.ToArray());
            return JsonHelper.ToJson(keywordList);
        }

        //查询高频词
        public string QueryGKeyword(params KeyValuePair<string, string>[] ps)
        {
            SearchKeywordBiz keywBiz = new SearchKeywordBiz();
            var keywordList = keywBiz.QueryKeyword(ps);
            return JsonHelper.ToJson(keywordList);
        }

        //查询扩展词
        public string QueryEKeyword(string keywords)
        {
            string ExpanWords = "";//扩展词
            string userId = "48f3889c-af8d-401f-ada2-c383031af92d1";
            string keyw = keywords.Substring(0, keywords.Length - 1);
            keyw = keyw.Substring(keyw.LastIndexOf(" ") + 1);
            List<SearchKeywordInfo> keywordList = new List<SearchKeywordInfo>();
            //查找用户主题分类,并根据主题优先级从高到低排序
            ZnkzBiz znkzBiz = new ZnkzBiz();
            DataTable dt = znkzBiz.getUserSubject(userId);
            //遍历每个主题分类，获取扩展词
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //匹配词匹配
                if (dt.Rows[i]["MATCH"].ToString() == "1")
                {
                    string keyws = dt.Rows[i]["KEYW"].ToString();//匹配词
                    string[] keywArr = keyws.Split('#');//匹配词数组
                    //匹配词匹配关键词
                    if (matchKeyw(keyw, keywArr))
                    {
                        ExpanWords = dt.Rows[i]["EXT_CONT"].ToString();//扩展词
                        string [] expanArr=ExpanWords.Split('#');
                        for (int k = 0; k < expanArr.Length; k++)
                        {
                            SearchKeywordInfo keywordInfo = new SearchKeywordInfo();
                            keywordInfo.KeywID = 0;
                            keywordInfo.Keyword = expanArr[k].ToString();
                            keywordList.Add(keywordInfo);
                        }
                        break;
                    }

                }//匹配词匹配

                //表字段匹配
                else if (dt.Rows[i]["MATCH"].ToString() == "2")
                {
                    string sqlStr = dt.Rows[i]["WHERE_FMT"].ToString() + " '%" + keyw + "%'";
                    //根据查询字符串搜索扩展词
                    DataTable dt1 = znkzBiz.getExpanWordsBySql(sqlStr);
                    if (dt1.Rows.Count != 0)
                    {
                       
                        ExpanWords = dt.Rows[i]["EXT_CONT"].ToString();//扩展词
                        string[] expanArr = ExpanWords.Split('#');
                        for (int k = 0; k < expanArr.Length; k++)
                        {
                            SearchKeywordInfo keywordInfo = new SearchKeywordInfo();
                            keywordInfo.KeywID = 0;
                            keywordInfo.Keyword = expanArr[k].ToString();
                            keywordList.Add(keywordInfo);
                        }
                        break;

                    }

                }//表字段匹配

                //匹配词和表字段匹配
                else if (dt.Rows[i]["MATCH"].ToString() == "3")
                {
                    string keyws = dt.Rows[i]["KEYW"].ToString();//匹配词
                    string[] keywArr = keyws.Split('#');//匹配词数组

                    string sqlStr = dt.Rows[i]["WHERE_FMT"].ToString() + " '%" + keyw + "%'";
                    //根据查询字符串搜索扩展词
                    DataTable dt1 = znkzBiz.getExpanWordsBySql(sqlStr);
                    //匹配词匹配关键词
                    if (matchKeyw(keyw, keywArr) || dt1.Rows.Count != 0)
                    {
                        ExpanWords = dt.Rows[i]["EXT_CONT"].ToString();//扩展词
                        string[] expanArr = ExpanWords.Split('#');
                        for (int k = 0; k < expanArr.Length; k++)
                        {
                            SearchKeywordInfo keywordInfo = new SearchKeywordInfo();
                            keywordInfo.KeywID = 0;
                            keywordInfo.Keyword = expanArr[k].ToString();
                            keywordList.Add(keywordInfo);
                        }
                        break;

                    }

                } //匹配词和表字段匹配

            }
            //SearchKeywordInfo keywordInfo1= new SearchKeywordInfo();
            //keywordInfo1.KeywID = 0;
            //keywordList.Add(keywordInfo1);
            return JsonHelper.ToJson(keywordList);
        }
        // 匹配词匹配关键词
        public bool matchKeyw(string keyw, string[] keywArr)
        {
            for (int i = 0; i < keywArr.Length; i++)
            {
                if (keyw.Equals(keywArr[i].ToString()))
                {
                    return true;
                   
                }
            }
            return false;
        }
        public bool AddKeyword(HttpContext context)
        {
            string keyw = context.Request.Params.Get("keyw");
            if (string.IsNullOrWhiteSpace(keyw)) return true;
            
            SearchKeywordBiz keywBiz = new SearchKeywordBiz();
            SearchKeywordInfo keywordInfo = new SearchKeywordInfo
            {
                Keyword = keyw.Replace("\\","").Replace("'","").Replace("%","").Replace("@","")
            };
            return keywBiz.AddKeyword(keywordInfo);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}